package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.tools.DateTimePickDialogUtil;
import com.ihighest.app.infox.tools.RegexKit;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 修改资料界面
 * 
 * @author lkx Created at 2015-10-5 下午7:59:46
 * @version 1.0
 */
public class AlertInfoActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
	private ActivityTitle title;
	private final String initStartDateTime = "1980年10月31日"; // 初始化开始时间
	private TextView birthDay;
	private EditText userName, userMemo, userQQ, userEmail, userCardId, userAddress;
	private RadioButton male, female;
	private String gender;// 性别

	/* 头像名称 */
	private Bitmap myBitmap;
	private static final String PHOTO_FILE_NAME = "card_photo.jpg";
	private File tempFile;
	// private String imgPath;
	private Uri photoUri;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private ImageView cardPositive, cardnNegative;
	private int image;// 选中的是正面还是反面的标识，0表示正面，1标识反面
	private ApiParam param;
	File fTemp1 = null;// 正面临时文件
	File fTemp2 = null;// 反面临时文件
	private String card1;
	private String card2;
	static Bitmap bitmap = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_alertinfo);
		initView();
		initData();
	}

	/**
	 * 初始加载会员信息
	 * 
	 * 
	 * @author lkx Created at 2015-11-4 上午10:49:35
	 */
	private void initData() {
		if (!TextUtils.isEmpty(SharedPreferencesKit.getString(AlertInfoActivity.this, Const.SP_KEY_USER_ID))) {
			String url = "member/info/m_" + SharedPreferencesKit.getString(AlertInfoActivity.this, Const.SP_KEY_USER_ID) + ".json";
			Api.data(url, new ApiCallback(AlertInfoActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						String name = result.getData().getString("title");
						String gender = result.getData().getString("sex");
						String birth = result.getData().getString("bir");
						String address = result.getData().getString("addr");
						String eMail = result.getData().getString("mail");
						String QQ = result.getData().getString("qq");

						card1 = result.getData().getString("pic1");
						card2 = result.getData().getString("pic2");
						String memo = result.getData().getString("memo");
						userName.setText(name);
						birthDay.setText(birth);
						userMemo.setText(memo);
						userQQ.setText(QQ);
						userEmail.setText(eMail);
						userAddress.setText(address);
						if (gender.equals("m")) {
							male.setChecked(true);
						}
						if (gender.equals("f")) {
							female.setChecked(true);

						}

						// DisplayImageOptions defaultOptions = new
						// DisplayImageOptions.Builder()
						// .showImageForEmptyUri(R.drawable.infox_img_loadrong).showImageOnFail(R.drawable.infox_img_loadrong)
						// .showImageOnLoading(R.drawable.infox_img_loadrong).cacheInMemory(true).cacheOnDisc(true).build();
						AppKit.SetNormalImg(card1, cardPositive);
						AppKit.SetNormalImg(card2, cardPositive);
						// ImageLoader.getInstance().displayImage(card1,
						// cardPositive, defaultOptions);
						// ImageLoader.getInstance().displayImage(card2,
						// cardnNegative, defaultOptions);

					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					// TODO Auto-generated method stub

				}
			}, AlertInfoActivity.this);
		}

	}

	/**
	 * 初始化
	 * 
	 * 
	 * @author lkx Created at 2015-10-13 下午2:20:35
	 */
	private void initView() {
		title = (ActivityTitle) findViewById(R.id.infox_alertInfoActivity_title);
		title.setTitle("修改资料");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("提交");
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		param = ApiParam.create();
		birthDay = (TextView) findViewById(R.id.userBirthday);
		userAddress = (EditText) findViewById(R.id.alertInfoAddress);
		userName = (EditText) findViewById(R.id.alertInfoUserName);
		userQQ = (EditText) findViewById(R.id.alertInfoQQ);
		userEmail = (EditText) findViewById(R.id.alertInfoEmail);
		userCardId = (EditText) findViewById(R.id.alertInfoActivitCardNumber);
		userMemo = (EditText) findViewById(R.id.alertInfoMemo);
		male = (RadioButton) findViewById(R.id.rbMale);
		female = (RadioButton) findViewById(R.id.rbFemale);
		cardPositive = (ImageView) findViewById(R.id.cardImgFrontage);
		cardPositive.setOnClickListener(this);
		cardnNegative = (ImageView) findViewById(R.id.cardImgback);

		cardnNegative.setOnClickListener(this);
		male.setOnCheckedChangeListener(this);
		female.setOnCheckedChangeListener(this);
		// 默认选中男
		gender = "m";
		male.setChecked(true);
		param.addParam("sex", gender);
		title.rightText.setOnClickListener(this);
		findViewById(R.id.birthDayLayout).setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.birthDayLayout:
			DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(AlertInfoActivity.this, initStartDateTime);
			dateTimePicKDialog.dateTimePicKDialog(birthDay);
			break;
		case R.id.infox_activitytitle_rightText:
			if (!TextUtils.isEmpty(SharedPreferencesKit.getString(AlertInfoActivity.this, Const.SP_KEY_USER_ID))) {
				commit();
			} else {
				ToastKit.showShort(AlertInfoActivity.this, Const.UN_LOGIN_ALERT);
			}

			break;
		case R.id.cardImgFrontage:
			image = 0;
			chooseImg();

			break;
		case R.id.cardImgback:
			image = 1;
			chooseImg();

			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton rb, boolean ischeck) {
		if (ischeck) {
			switch (rb.getId()) {
			case R.id.rbMale:
				gender = "m";
				param.addParam("sex", gender);
				break;

			case R.id.rbFemale:
				gender = "f";
				param.addParam("sex", gender);
				break;
			}
		}

	}

	private void chooseImg() {
		new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

			}
		}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {

				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				// 判断存储卡是否可以用，可用进行存储
				if (hasSdcard()) {
					ContentValues values = new ContentValues();
					photoUri = AlertInfoActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
				}
				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
			}
		}).show();
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * 
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				if (tempFile != null) {
					crop(Uri.fromFile(tempFile));
				}

			} else {
				Toast.makeText(AlertInfoActivity.this, "未找到存储卡，无法存储照片！", 0).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				if (image == 0) {

					this.cardPositive.setImageBitmap(myBitmap);
				}
				if (image == 1) {
					this.cardnNegative.setImageBitmap(myBitmap);
				}
				upload();
				boolean delete = tempFile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * 
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 图片数据拼接
	 * 
	 * 
	 * @author lkx Created at 2015-10-17 下午2:45:38
	 */
	private void upload() {
		if (myBitmap != null) {
			BufferedOutputStream bos = null;

			try {
				if (image == 0) {// 正面证件照
					System.out.println("正面");
					fTemp1 = File.createTempFile("card", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp1));
				}
				if (image == 1) {// 反面证件照
					System.out.println("反面");
					fTemp2 = File.createTempFile("card2", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp2));
				}
				// fTemp = File.createTempFile("card", ".jpg");

				// BufferedOutputStream bos = new BufferedOutputStream(new
				// FileOutputStream(fTemp));
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (image == 0) {// 正面证件照
				param.addParam("pic1", fTemp1);
			}
			if (image == 1) {// 反面证件照
				param.addParam("pic2", fTemp2);
			}

		}

	}

	/**
	 * 提交数据
	 * 
	 * 
	 * @author lkx Created at 2015-11-3 上午10:53:44
	 */
	private void commit() {
		if (TextUtils.isEmpty(userName.getText().toString())) {
			ToastKit.showShort(AlertInfoActivity.this, "请输入真实姓名");

		} else {
			param.addParam("title", userName.getText().toString());
			if (TextUtils.isEmpty(birthDay.getText().toString())) {
				ToastKit.showShort(AlertInfoActivity.this, "请选择出生年月");
			} else {
				param.addParam("bir", birthDay.getText().toString());
				if (TextUtils.isEmpty(userCardId.getText().toString())) {
					ToastKit.showShort(AlertInfoActivity.this, "请输入身份证号码");

				} else {
					if (!RegexKit.personIdValidation(userCardId.getText().toString())) {
						ToastKit.showShort(AlertInfoActivity.this, "请输入正确的身份证号码");
					} else {
						param.addParam("identity", userCardId.getText().toString());
						if (TextUtils.isEmpty(userMemo.getText().toString())) {

							ToastKit.showShort(AlertInfoActivity.this, "请输入个人简介");
						} else {

							param.addParam("memo", userMemo.getText().toString());
							if (fTemp1 == null) {
								if (TextUtils.isEmpty(card1)) {
									ToastKit.showShort(AlertInfoActivity.this, "请选择证件照正面");
									return;
								} else {
									// URI ui = null;
									// try {
									// ui = new URI(card1);
									// } catch (URISyntaxException e1) {
									// // TODO Auto-generated catch block
									// e1.printStackTrace();
									// }

									// File fifle = new File(ui);
									cardPositive.setDrawingCacheEnabled(true);

									param.addParam("pic1", upload(cardPositive.getDrawingCache()));
									if (TextUtils.isEmpty(card2)) {
										ToastKit.showShort(AlertInfoActivity.this, "请选择证件反面");
										return;
									} else {
										// URI ui = null;
										// try {
										// ui = new URI(card2);
										// } catch (URISyntaxException e1) {
										// // TODO Auto-generated catch block
										// e1.printStackTrace();
										// }
										// File fifle = new File(ui);
										cardnNegative.setDrawingCacheEnabled(true);
										cardnNegative.getDrawingCache();
										param.addParam("pic2", upload(cardnNegative.getDrawingCache()));
										// param.addParam("pic2", fifle);
									}
								}

							} else if (fTemp2 == null) {
								if (TextUtils.isEmpty(card2)) {
									ToastKit.showShort(AlertInfoActivity.this, "请选择证件反面");
									return;
								} else {
									// URI ui = null;
									// try {
									// ui = new URI(card2);
									// } catch (URISyntaxException e1) {
									// // TODO Auto-generated catch block
									// e1.printStackTrace();
									// }
									// File fifle = new File(ui);
									cardnNegative.setDrawingCacheEnabled(true);
									cardnNegative.getDrawingCache();
									param.addParam("pic2", upload(cardnNegative.getDrawingCache()));
									// param.addParam("pic2", fifle);
								}

							}
							title.rightText.setClickable(false);
							Api.post("me/update", param, new ApiCallback(AlertInfoActivity.this) {

								@Override
								public void handleSuccess(ApiResult result) {
									cardPositive.setDrawingCacheEnabled(false);
									cardnNegative.setDrawingCacheEnabled(false);
									finish();
								}

								@Override
								public void handleFailure(Exception e, String msg) {
									title.rightText.setClickable(true);
								}
							}, AlertInfoActivity.this);
						}
					}

				}

			}

		}

		if (!TextUtils.isEmpty(userAddress.getText().toString())) {
			param.addParam("addr", userAddress.getText().toString());
		}

		if (!TextUtils.isEmpty(userEmail.getText().toString())) {
			param.addParam("mail", userEmail.getText().toString());
		}
		if (!TextUtils.isEmpty(userQQ.getText().toString())) {
			param.addParam("qq", userQQ.getText().toString());
		}

	}

	// /**
	// * 得到本地或者网络上的bitmap url - 网络或者本地图片的绝对路径,比如:
	// *
	// * A.网络路径: url="http://blog.foreverlove.us/girl2.png" ;
	// *
	// * B.本地路径:url="file://mnt/sdcard/photo/image.png";
	// *
	// * C.支持的图片格式 ,png, jpg,bmp,gif等等
	// *
	// * @param url
	// * @return
	// */
	// public static Bitmap GetLocalOrNetBitmap(final String url) {
	//
	// new Thread() {
	//
	// private URL myFileUrl;
	//
	// @Override
	// public void run() {
	// try {
	// myFileUrl = new URL(url);
	// } catch (MalformedURLException e) {
	// e.printStackTrace();
	// }
	// try {
	// HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
	// conn.setDoInput(true);
	// conn.connect();
	// InputStream is = conn.getInputStream();
	// bitmap = BitmapFactory.decodeStream(is);
	// is.close();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// super.run();
	// }
	// }.start();
	//
	// return bitmap;
	// }

	private File upload(Bitmap map) {
		File createTempFile = null;
		if (map != null) {
			BufferedOutputStream bos = null;

			try {

				createTempFile = File.createTempFile("card", ".jpg");
				bos = new BufferedOutputStream(new FileOutputStream(createTempFile));

				// fTemp = File.createTempFile("card", ".jpg");

				// BufferedOutputStream bos = new BufferedOutputStream(new
				// FileOutputStream(fTemp));
				map.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return createTempFile;

	}
}
